import Vue from 'vue'
import { cacheConfig } from '@cache'

// 时间戳
Vue.filter('dateFormat', function (value, fmt) {
  if(value==0||!value){
    return '-'
  }
  let getDate = new Date(value*1000);
  let o = {
    'M+': getDate.getMonth() + 1,
    'd+': getDate.getDate(),
    'H+': getDate.getHours(),
    'm+': getDate.getMinutes(),
    's+': getDate.getSeconds(),
    'q+': Math.floor((getDate.getMonth() + 3) / 3),
    'S': getDate.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt;
});

//格式化文件大小
Vue.filter('formatSize', function (value) {
  if(!value || value < 0 || isNaN(value)) {
    return "0 Bytes";
  }
  let unitArr = new Array("Bytes","K","M","G","TB","PB","EB","ZB","YB");
  let index=0;
  let srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize)/Math.log(1024));
  var size =srcsize/Math.pow(1024, index)
  size=size.toFixed(2)//保留的小数位数
  return size+unitArr[index]
})

// 返回 config
Vue.filter('config', function (value) {
  let config = cacheConfig.load()
  let re = '-'
  if (value && config) {
    let p = value.split('.')
    if (config[p[0]]) {
      re = config[p[0]]
      if (p[1] && config[p[0]][p[1]]) {
        re = config[p[0]][p[1]]
      }
    }
  }  
  return re
});
// 日期单位
Vue.filter('dateUnit', (val)=> {
  let res
  let goods_price_unit = cacheConfig.load().goods_price_unit
  goods_price_unit.forEach(el => {
    if(val === el.key) {
      res =  el.name
    }
  });
  return res
})
// 产品价格分类
Vue.filter('goodPriceType', (val)=> {
  let res
  let goods_price_type = cacheConfig.load().goods_price_type
  goods_price_type.forEach(el => {
    if(val === el.key) {
      res =  el.name
    }
  });
  return res
})
// 产品单位
Vue.filter('goodUnit', (val)=> {
  let res
  let goods_unit = cacheConfig.load().goods_unit
  goods_unit.forEach(el => {
    if(val === el.key) {
      res =  el.name
    }
  });
  return res
})
// 千位分割
Vue.filter('thousandSeparate', function (argNum) {
  let num = argNum == null || argNum == '' || argNum == undefined ? 0 : Number(argNum)
  let str = num.toFixed(3);
  let arr = [];
  let re = /(?=(?!\b)(\d{3})+$)/g;
  if (str.indexOf(".") >= 0) {
    arr = str.split(".");
    str = arr[0].replace(re, ",") + "." + arr[1];
  } else {
    str = str.replace(re, ",");
  }
  return str;
})